package com.huluobo.a2110mvpimdemo.base;

import java.lang.ref.WeakReference;

import io.reactivex.disposables.CompositeDisposable;

/**
 * Created by LC on 2023/12/8.
 * P层基准类
 * 内存引用的4中形式 强 弱 软 虚
 * 1.强引用- User user = new User(),程序宁可报错,也不会销毁(回收)当前的引用
 * 2.弱引用- WeakReference<User> user = new WeakReference(), 只要发生GC(垃圾回收机制),就会回收掉
 * 3.软引用- SoftReference<User> user= new SoftReference(),只要内存不足,就会回收掉
 * 4.虚引用- 一般不用,有时候可能都拿不到对象,new不出来
 */
public class BasePresenter<V> {
    private WeakReference<V> weakReference;//声明需要使用弱引用的View对象,当发生垃圾回收时,就会销毁View对象

    protected CompositeDisposable compositeDisposable = new CompositeDisposable();//解决P层内存泄漏


    //绑定视图
    public void attachView(V view) {
        if (weakReference == null) {
            weakReference = new WeakReference<>(view);
        }
    }

    //解绑视图
    public void disAttach() {
        if (weakReference != null) {
            weakReference.clear();
            weakReference = null;
        }

        if (compositeDisposable != null) {
            compositeDisposable.clear();
            compositeDisposable = null;
        }
    }

    //判断当前View层是否已经被P层绑定(是否添加到了弱引用当中)
    // weakReference.get() 获取当前弱引用中的view
    public Boolean isAttach() {
        return weakReference != null && weakReference.get() != null;
    }

    //获取当前的view
    public V getView() {
        if (weakReference != null && weakReference.get() != null) {
            return weakReference.get();
        }
        return null;
    }
}
